package com.hegongda.okcmall.product.service.impl;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.hegongda.okcmall.product.entity.AttrAttrgroupRelationEntity;
import com.hegongda.okcmall.product.entity.AttrEntity;
import com.hegongda.okcmall.product.service.AttrAttrgroupRelationService;
import com.hegongda.okcmall.product.service.AttrService;
import com.hegongda.okcmall.product.vo.AttrGroupWithAttrsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hegongda.common.utils.PageUtils;
import com.hegongda.common.utils.Query;

import com.hegongda.okcmall.product.dao.AttrGroupDao;
import com.hegongda.okcmall.product.entity.AttrGroupEntity;
import com.hegongda.okcmall.product.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationService attrgroupRelationService;

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils query(Map<String, Object> params, Integer catelogId) {
        // 当catelogId为0 默认查询全部
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
        if (catelogId == 0){
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),queryWrapper);
            return new PageUtils(page);
        } else {
            /**
             *  先根据三级分类进行查询，
             *  然后根据传入的Id进行匹配模糊查询
             */
            queryWrapper.eq("catelog_id", catelogId);
            String key = (String) params.get("key");
            if (StringUtils.isNotEmpty(key)){
                queryWrapper.and((obj) -> {
                   obj.eq("attr_group_id", key).or().like("attr_group_name", key);
                });
            }
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),queryWrapper);
            return new PageUtils(page);
        }
    }

    @Override
    public AttrGroupEntity selectOne(Long attrGroupId) {
        return baseMapper.selectById(attrGroupId);
    }

    @Override
    public List<AttrEntity> getAttrRelation(String groupId) {
        // 通过中见表查到 attr_id
        List<Long> attrIds = attrgroupRelationService.getAttrIds(groupId);
        // 通过attr_id 查 AttrEntity
        if (attrIds != null && attrIds.size() > 0) {
            List<AttrEntity> attrEntities = (List<AttrEntity>) attrService.listByIds(attrIds);
            return attrEntities;
        }
        return null;
    }

    @Override
    public void deleteAttrRelation(List<AttrAttrgroupRelationEntity> entities) {
        attrgroupRelationService.deleteRecoder(entities);
    }

    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long groupId) {
        // 查询的属性必须在该分组的分类下
        AttrGroupEntity groupEntity = baseMapper.selectById(groupId);
        // 获取分类ID
        Long catelogId = groupEntity.getCatelogId();
        // 并且分组与分类不在该关系表中
        PageUtils page = attrService.queryNOAttrPage(params,catelogId,1, groupId);
        return page;
    }

    /**
     *  分组下关联属性
     * @param attrGroupEntities
     */
    @Override
    public void saveBatchRelation(List<AttrAttrgroupRelationEntity> attrGroupEntities) {
        attrGroupEntities.forEach((entity) -> attrgroupRelationService.save(entity));
    }

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrs(String catelogId) {
        List<AttrGroupEntity> groupList = baseMapper
                .selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<AttrGroupWithAttrsVo> dataList = groupList.stream().map((group) -> {
            AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(group, vo);
            // 根据分组Id查询出其下的属性
            List<AttrAttrgroupRelationEntity> entities = attrgroupRelationService
                    .list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", group.getAttrGroupId()));
            List<Long> attrIds = entities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
            // 根据中间表查询出属性
            List<AttrEntity> entityList = attrService.list(new QueryWrapper<AttrEntity>().in("attr_id", attrIds));
            vo.setAttrs(entityList);
            return vo;
        }).collect(Collectors.toList());

        return dataList;
    }

}